package com.bjpowernode.dataservice.service;

import com.bjpowernode.api.model.Recharge;
import com.bjpowernode.api.serivce.RechargeService;
import com.bjpowernode.constants.Constant;
import com.bjpowernode.dataservice.mapper.FinanceAccountMapper;
import com.bjpowernode.dataservice.mapper.RechargeMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author 麦翔盛
 * @ClassName: RechargeServiceImpl
 * @Package: com.bjpowernode.dataservice.service
 * @description: 充值接口
 * @date 2022/5/31 16:06
 */
@DubboService(interfaceClass = RechargeService.class, version = "1.0")
public class RechargeServiceImpl implements RechargeService {
    @Resource
    RechargeMapper rechargeMapper;

    @Resource
    FinanceAccountMapper financeAccountMapper;


    @Override
    public int createNewRechargeOrder(Recharge recharge) {
        int add = rechargeMapper.insertSelective(recharge);
        return add;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized void doRechargeHandler(String orderId, String payAmount, String payResult) {
        int rows = 0;
        //查询订单
        if (orderId == null || payAmount == null || payResult == null){
            throw new RuntimeException("参数异常");
        }
        //查询支付订单
        Recharge recharge = rechargeMapper.selectByOrderNoForUpdate(orderId);
        if (recharge == null){
            throw new RuntimeException("订单为空");
        }
        //获取订单数据
        Integer status = recharge.getRechargeStatus();
        //如果该订单的状态不是0，不处理该订单
        if (!status.equals(Constant.RECHARGE_PROCESSING_0)){
            throw new RuntimeException("该订单状态不为0，该订单已经处理过了");
        }


        BigDecimal rechargeMoney = recharge.getRechargeMoney();
        String fen = rechargeMoney
                .multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        //校验金额是否正确
        if (!fen.equals(payAmount)){
            throw new RuntimeException("充值金额对不上");
        }

        //校验支付状态是否为10
        if (Constant.PAY_RESULT_SUCCESS.equals(payResult)){
            //成功，修改账户余额
            rows = financeAccountMapper.updateMoneyAdd(recharge.getUid(),recharge.getRechargeMoney());
            if(rows < 1){
                throw new RuntimeException("给用户账户充值失败");
            }
            //校验成功,更新支付状态
            rows = rechargeMapper.updateStatus(recharge.getId(),Constant.RECHARGE_SUCCESS_1);
            if (rows < 1){
                throw new RuntimeException("修改订单状态为1失败");
            }
        }else{
            //支付失败修改订单状态为2
            rows = rechargeMapper.updateStatus(recharge.getId(),Constant.RECHARGE_FAIL_2);
            if (rows < 1){
                throw new RuntimeException("修改订单状态为2失败");
            }
        }


    }
}
